package com.xiaoyu.lanling.feature.board.controller

import `in`.srain.cube.views.list.CubeRecyclerViewAdapter
import `in`.srain.cube.views.list.CubeRecyclerViewSimpleAdapter
import `in`.srain.cube.views.list.PagedListDataModelWithRequestTag
import android.content.Context
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.base.view.list.BaseListViewController
import com.xiaoyu.lanling.event.board.BoardListEvent
import com.xiaoyu.lanling.feature.board.model.BoardItem
import com.xiaoyu.lanling.feature.board.viewholder.BoardViewHolder
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class BoardController constructor(context: Context,
                                  listData: PagedListDataModelWithRequestTag<BoardItem, Any>,
                                  adapter: CubeRecyclerViewAdapter<BoardItem>,
                                  swipeRefreshLayout: SwipeRefreshLayout,
                                  recyclerView: RecyclerView) :
        BaseListViewController<BoardItem, Any>(
                context,
                listData,
                adapter,
                swipeRefreshLayout,
                recyclerView) {

    companion object {

        fun create(context: Context, listData: PagedListDataModelWithRequestTag<BoardItem, Any>, swipeRefreshLayout: SwipeRefreshLayout, recyclerView: RecyclerView, emptyView: View? = null): BoardController {

            val adapter = CubeRecyclerViewSimpleAdapter<BoardItem>()
            adapter.setViewHolderClass(0, null, BoardViewHolder::class.java, 20)

            val controller = BoardController(context, listData, adapter, swipeRefreshLayout, recyclerView)

            AppEventBus.bindContainerAndHandler(context, object : SimpleEventHandler() {

                @Subscribe(threadMode = ThreadMode.MAIN)
                fun onDataLoad(event: BoardListEvent) {
                    if (listData.listPageInfo.isEmpty) {
                        emptyView?.visibility = View.VISIBLE
                    } else {
                        emptyView?.visibility = View.GONE
                    }
                    controller.onListEvent(event)
                }
            })
            return controller
        }
    }
}